<template>
  <div class="op-container">
    <k-button class="top-btn" value="创建自定义站内信" @click.native="openCustomEmailDialog" />
    <div v-show="false" class="top-right-btn">
      <k-button value="站内信类型配置" @click.native="emailTypeSettingDialog" />
    </div>
    <!--表格相关 -->
    <el-table
      :data="messageList"
      fit
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
    >
      <el-table-column type="index" label="序号" width="60px" align="center" />
      <el-table-column prop="title" min-width="200px" label="主题" align="center" show-overflow-tooltip />
      <el-table-column prop="userNames" min-width="200px" label="收件人" align="center" show-overflow-tooltip />
      <el-table-column prop="creatorName" min-width="120px" label="创建人" align="center" show-overflow-tooltip />
      <el-table-column prop="createTime" min-width="200px" label="创建时间" align="center" show-overflow-tooltip />
      <el-table-column min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="详情" @click.native="checkMessageDialog(scope.row)" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />
    <!-- 创建自定义站内信弹窗 -->
    <k-dialog
      :show-hide.sync="openCustomEmail.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      class-name="openCreateEmail-dialog"
      :show-foot="false"
      :two-btn="dialogStatus==='create'"
      :close-fun="handleCloseDialog"
      @click="saveCustomNotice"
    >
      <div class="dialog-openCustomEmail">
        <el-form :model="customMessageModel" label-width="auto">
          <div style="display:flex;">
            <el-form-item v-show="dialogStatus==='create'" label="指定用户：">
              <search-select
                ref="KsearchSelect"
                :result-list="winnerUserList"
                :readonly-state="mesType"
                @requestReslutList="requestReslutList"
                @selectChange="selectChange"
                @visibleChange="visibleChange"
              />
            </el-form-item>
            <p v-show="customMessageModel.allUser">已选择所有用户</p>
            <k-button
              v-show="dialogStatus==='create'"
              class="balance_btn"
              :disabled="mesType"
              :value="customMessageModel.allUser ? '取消':'所有用户'"
              @click.native="customMessageModel.allUser = !customMessageModel.allUser"
            />
          </div>
          <el-form-item v-show="dialogStatus==='create'" label="指定主播群组：">
            <el-select
              v-model="customMessageModel.fissionId"
              filterable
              clearable
              :disabled="checkedIdList.length > 0 || customMessageModel.allUser"
              placeholder="请选择指定主播"
              @change="changeFissionId($event)"
              @clear="clearChange"
            >
              <el-option v-for="item in belongList" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
            </el-select>
          </el-form-item>

          <el-form-item label="站内信主题：" prop="title">
            <el-input v-model="customMessageModel.title" show-word-limit placeholder="请输入站内信主题" />
          </el-form-item>
          <el-form-item label="站内信内容：" prop="content">
            <quill-editor
              ref="myQuillEditor"
              v-model.trim="customMessageModel.content"
              :options="editorOption"
              class="editer"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
  </div>
</template>
<script>
import { listShowData, postNotice } from '@/api/message/message'
import { getAllWebUser } from '@/api/red/data'
import { getAnchors } from '@/api/user/user'
import Pagination from '@/components/Pagination'
import SearchSelect from '@/components/SearchSelect'

export default {
  components: { Pagination, SearchSelect },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  props: {
    type: {
      type: String,
      default: 'message'
    }
  },
  data() {
    return {
      mesType: false,
      customMessageModel: {
        allUser: false,
        userIds: [],
        fissionId: '',
        title: '',
        content: ''
      },
      checkedIdList: [],
      winnerUserList: [],
      messageTypeList: [],
      belongList: [],
      messageList: [],
      emailTypeSettingModel: {
        types: [{
          value: ''
        }],
        email: ''
      },
      dialogStatus: 'create',
      textMap: {
        update: '详情',
        create: '创建站内信'
      },
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '' // 排序 正向(asc)逆向(desc),
      },
      messageInfo: {
        id: undefined, // 主键id",
        title: '', // 标题",
        status: 0, // 开关0关1开",
        content: '', // 内容",
        type: 2, // 1公告2站内信",
        secType: undefined, // 站内信类型",
        secTypeName: '', // 站内信类型名称",
        creatorId: undefined, // 创建者id",
        crtTime: '', // 创建时间",
        updTime: '', // 修改时间",
        updateId: undefined // 修改人id"
      },
      editorOption: { //  富文本编辑器配置
        placeholder: '请输入内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ 'header': 1 }, { 'header': 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
            [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
            [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
            [{ 'direction': 'rtl' }], // 文本方向
            [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
            [{ 'font': [] }], // 字体
            [{ 'align': [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image'] // 上传图片、上传视频
          ]
        }
      },
      email: {
        type: '',
        title: '',
        content: ''
      },
      openCreateEmail: {
        showHide: false
      },
      openCustomEmail: {
        showHide: false
      },
      emailTypeSetting: {
        showHide: false
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    clearChange() {
      this.customMessageModel.fissionId = undefined
      this.mesType = false
    },

    loadData() {
      listShowData(this.listQuery).then(res => {
        this.messageList = res.data.rows
        this.totalRows = res.data.totalRows
        this.$log(res)
      })
    },
    // 请求推广用户返回列表
    requestReslutList(value) {
      getAllWebUser({ key: value }).then(res => {
        this.winnerUserList = []
        Object.assign(this.winnerUserList, res.data)
        // this.$log('checkedIdList ', this.winnerUserList)
        this.winnerUserList = this.winnerUserList.filter(item => !this.checkedIdList.includes(item.id))
        // this.$log(this.checkedIdList, this.winnerUserList)
      })
    },
    selectChange(checkedList) {
      this.customMessageModel.userIds = checkedList.map(item => {
        return item.id
      })
      this.checkedIdList = []
      this.checkedIdList = checkedList.map(item => {
        return item.id
      })
    },
    visibleChange() {
      this.winnerUserList = []
    },
    // 发送自定义站内信
    saveCustomNotice() {
      if (this.customMessageModel.allUser) {
        this.$confirm('确定要发送站内信到【所有用户】吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          postNotice(this.customMessageModel).then(res => {
            this.$log(res)
            this.$message.success('发送成功')
            this.$resetForm(this.customMessageModel)
            this.loadData()
          })
          this.handleCloseDialog()
        }).catch(() => {
        })
        return
      }
      postNotice(this.customMessageModel).then(res => {
        this.$log(res)
        this.$message.success('发送成功')
        this.$resetForm(this.customMessageModel)
        this.loadData()
      })
      this.handleCloseDialog()
    },
    handleCloseDialog() {
      this.openCustomEmail.showHide = false
      this.$nextTick(() => {
        this.$refs.KsearchSelect.checkedList = []
        this.$refs.KsearchSelect.selectValueList = []
      })
    },
    openCustomEmailDialog() {
      this.$resetForm(this.customMessageModel)
      this.winnerUserList = []
      this.checkedIdList = []
      this.dialogStatus = 'create'
      this.mesType = false
      getAnchors().then(res => {
        this.openCustomEmail.showHide = true
        this.belongList = res.data.data
      })
    },
    emailTypeSettingDialog() {
      this.emailTypeSetting.showHide = true
    },
    checkMessageDialog(row) {
      this.openCustomEmail.showHide = true
      this.dialogStatus = 'update'
      this.customMessageModel.title = row.title
      this.customMessageModel.content = row.content
    },

    changeFissionId(res) {
      this.customMessageModel.fissionId = res
      this.mesType = true
    }
  }
}
</script>
<style lang="scss" scoped>
$mainColor: #3b425d; // 主色调
$disabledColor: #909399; //禁用色
$hoverColor: #1D143C; // 鼠标停留主色调浅色

.balance_btn {
  margin-left: 20px;
  font-size: 14px;
  height: 45px;
  color: #ffffff;
}

.op-container {
  margin: 20px;
}

.top-btn {
  margin: 10px 10px 30px 0px;
  font-size: 14px;
  color: #ffffff;
}

.top-right-btn {
  position: absolute;
  right: 20px;
  top: 30px;

  ::v-deep .el-button {
    background-color: #F8F7FB;
    border-color: transparent;
    color: #14162E;

    &:hover {
      color: #ffffff;
      background-color: $mainColor;
    }

    &:active {
      color: #14162E;
    }
  }
}

::v-deep .el-select .el-input.is-focus .el-input__inner {
  border-color: $mainColor;
}

.dialog-openCustomEmail {
  ::v-deep .el-select .el-input__inner {
    width: 500px;
  }
}

::v-deep .el-input__inner:focus {
  border-color: $mainColor;
}

.editer {
  border-radius: 8px;
  float: left;
  box-sizing: border-box;
  color: #606266;

  ::v-deep .ql-container {
    height: 240px;
    border-radius: 0px 0px 8px 8px;
  }

  ::v-deep .ql-toolbar.ql-snow {
    border-radius: 8px 8px 0px 0px;
  }
}

.typesetting-item {
  ::v-deep .el-form-item__content {
    display: flex;
    flex-direction: row;
  }

  .el-icon {

    &-circle-plus,
    &-remove {
      font-size: 22px;
      color: #409EFF;
      display: flex;
      margin-left: 20px;
      flex-direction: column;
      justify-content: center;
    }
  }
}
</style>

